package com.codegeek.project.slope.controller;

import com.codegeek.common.utils.SecurityUtils;
import com.codegeek.common.utils.poi.ExcelUtil;
import com.codegeek.framework.aspectj.lang.annotation.Log;
import com.codegeek.framework.aspectj.lang.enums.BusinessType;
import com.codegeek.framework.web.controller.BaseController;
import com.codegeek.framework.web.domain.AjaxResult;
import com.codegeek.framework.web.page.TableDataInfo;
import com.codegeek.project.communicate.SlopeDTUService;
import com.codegeek.project.slope.domain.*;
import com.codegeek.project.slope.service.ISlopeDeviceService;
import com.codegeek.project.slope.service.ISlopeGlareService;
import com.codegeek.project.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 设备Controller
 *
 * @author codegeek
 * @date 2020-02-17
 */
@RestController
@RequestMapping("/slope/device")
@Api(value="设备Controller",tags={"设备操作接口"})
public class SlopeDeviceController extends BaseController
{
    @Autowired
    private ISlopeDeviceService slopeDeviceService;

    @Autowired
    private ISlopeGlareService slopeGlareService;

    /**
     * 查询设备列表
     */
    @ApiOperation("查询设备列表")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('slope:device:list')")
    public TableDataInfo list(SlopeDevice slopeDevice) {
        startPage();
        List<SlopeDevice> list = slopeDeviceService.selectSlopeDeviceList(slopeDevice);
        return getDataTable(list);
    }

    /**
     * 查询其他设备列表
     */
    @ApiOperation("查询其他设备列表")
    @GetMapping("/listOtherDevice")
    @PreAuthorize("@ss.hasPermi('slope:device:otherList')")
    public TableDataInfo listOtherDevice(SlopeDevice slopeDevice) {
        startPage();
        List<SlopeDevice> list = slopeDeviceService.selectSlopeOtherDeviceList(slopeDevice);
        return getDataTable(list);
    }

    @Autowired
    ISysDictDataService sysDictDataService;
    /**
     * 导出其他设备列表
     */
    @ApiOperation("导出其他设备列表")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @GetMapping("/exportOtherDevice")
    @PreAuthorize("@ss.hasPermi('slope:device:export')")
    public AjaxResult exportOtherDevice(SlopeDevice slopeDevice) {
        List<SlopeDevice> list = slopeDeviceService.selectSlopeOtherDeviceList(slopeDevice);
        List<SlopeDeviceData> deviceData = new LinkedList<>();
        for(SlopeDevice device : list){
            SlopeSupplier supply = device.getSupplier();
            SlopePoint point = device.getPoint();
            SlopeDeviceData slopeDeviceData = new SlopeDeviceData();
            try {
                slopeDeviceData.setId(device.getDeviceId());
                slopeDeviceData.setDeviceName(device.getDeviceName());
                slopeDeviceData.setState(sysDictDataService.selectDictLabel("sensor_state", device.getState() + ""));
                slopeDeviceData.setDeviceType(sysDictDataService.selectDictLabel("device_type", device.getDeviceType() + ""));
                slopeDeviceData.setSupplyName(supply.getSupplierName());
                slopeDeviceData.setSupplyRepo(supply.getSupplierRepo());
                slopeDeviceData.setSupplyPhone(supply.getSupplierPhone());
                slopeDeviceData.setNumber(device.getNumber());
                slopeDeviceData.setImei(device.getImei());
                slopeDeviceData.setPosition(point.getLon() + "," + point.getLat());
            }catch (Exception e){

            }finally {
                deviceData.add(slopeDeviceData);
            }
        }
        ExcelUtil<SlopeDeviceData> util = new ExcelUtil<>(SlopeDeviceData.class);
        return util.exportExcel(deviceData, "device");
    }

    @GetMapping("/importTemplate")
    @ApiOperation("导入设备模板")
    @PreAuthorize("@ss.hasPermi('slope:device:import')")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SlopeDeviceData> util = new ExcelUtil<>(SlopeDeviceData.class);
        return util.importTemplateExcel("设备数据");
    }

    /**
     * 导入设备列表
     */
    @ApiOperation("导入设备列表")
    @Log(title = "设备管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importDevice")
    @PreAuthorize("@ss.hasPermi('slope:device:import')")
    public AjaxResult importDevice(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SlopeDevice> util = new ExcelUtil<>(SlopeDevice.class);
        List<SlopeDevice> deviceList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        List<Map<String, Object>> imeiList = slopeDeviceService.selectAllDeviceImei();
        String message = slopeDeviceService.importDevice(deviceList, updateSupport, operName, imeiList);
        return AjaxResult.success(message);
    }

    /**
     * 获取设备详细信息
     */
    @ApiOperation("获取设备详细信息")
    @GetMapping(value = "/getInfo/{deviceId}")
    @PreAuthorize("@ss.hasPermi('slope:device:query')")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return AjaxResult.success(slopeDeviceService.selectSlopeDeviceById(deviceId));
    }

    /**
     * 新增设备
     */
    @ApiOperation("新增设备")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('slope:device:add')")
    @Transactional
    public AjaxResult add(@RequestBody SlopeDevice slopeDevice) {
        slopeDevice.setJoinTime(new Date());
        slopeDevice.setIsValid("0");
        slopeDevice.setCreateBy(SecurityUtils.getUsername());
        int iRet=slopeDeviceService.insertSlopeDevice(slopeDevice);
        //声光报警器
        if(iRet>0&&slopeDevice.getDeviceType()==2){
            SlopeGlare slopeGlare=new SlopeGlare();
            slopeGlare.setDeviceId(slopeDevice.getDeviceId());
            slopeGlare.setReserve("0");
            iRet= slopeGlareService.insertSlopeGlare(slopeGlare);
        }
        return toAjax(iRet);
    }

    /**
     * 修改设备
     */
    @ApiOperation("修改设备")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('slope:device:edit')")
    public AjaxResult edit(@RequestBody SlopeDevice slopeDevice) {
        return toAjax(slopeDeviceService.updateSlopeDevice(slopeDevice));
    }


    @Autowired
    private SlopeDTUService slopeDTUService;

    /**
     * 禁用启用设备
     */
    @ApiOperation("禁用启用设备")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/disable")
    @PreAuthorize("@ss.hasPermi('slope:device:disable')")
    public AjaxResult disable(@RequestBody SlopeDevice slopeDevice) {
        String isValid=slopeDevice.getIsValid();
        //禁用设备时，在线改离线
        if(isValid.equals("1")){
            slopeDevice=slopeDeviceService.selectSlopeDeviceById(slopeDevice.getDeviceId());
            slopeDevice.setIsValid(isValid);
            if(slopeDevice.getState()==1){
                slopeDevice.setState(0);
            }
            slopeDTUService.closeDevice(slopeDevice.getImei());
        }
        return toAjax(slopeDeviceService.updateSlopeDevice(slopeDevice));
    }

    /**
     * 删除设备
     */
    @ApiOperation("删除设备")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
	@PostMapping("/remove/{deviceIds}")
    @PreAuthorize("@ss.hasPermi('slope:device:remove')")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(slopeDeviceService.deleteSlopeDeviceByIds(deviceIds));
    }

    /**
     * 首页设备状态统计
     */
    @ApiOperation("首页设备状态统计")
    @GetMapping("/indexDeviceSum")
//    @PreAuthorize("@ss.hasPermi('slope:device:getStatistics')")
    public AjaxResult indexDeviceSum(){
        return AjaxResult.success(slopeDeviceService.countSlopeDeviceByState());
    }


    /**
     * 修改设备状态
     *   * 注：启用需要往设备最新维修记录中写入维修结束时间，
     *      *  维护需要创建维修记录
     */
    @ApiOperation("修改设备状态")
    @PostMapping("/editDeviceState")
    @PreAuthorize("@ss.hasPermi('slope:manage:repair')")
    public AjaxResult editDeviceState( Integer state , String devices){
        return AjaxResult.success(slopeDeviceService.editDeviceState(state,devices));
    }

}
